package com.zhongwang.mms.module.buy.model;

import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;

import java.util.List;

public class InvoiceTypeDropdownHandler implements SheetWriteHandler {

    private final List<String> options;
    private final int maxRow;   // 下拉生效行数

    public InvoiceTypeDropdownHandler(List<String> options, int maxRow) {
        this.options = options;
        this.maxRow = maxRow;
    }

    @Override
    public void afterSheetCreate(WriteWorkbookHolder wbh, WriteSheetHolder wsh) {
        Sheet sheet = wsh.getSheet();
        Workbook wb = wbh.getWorkbook();

        // 隐藏 sheet 存放下拉项
        String hiddenName = "hidden_invoice_type";
        Sheet hidden = wb.createSheet(hiddenName);
        for (int i = 0; i < options.size(); i++) {
            hidden.createRow(i).createCell(0).setCellValue(options.get(i));
        }
        wb.setSheetHidden(wb.getSheetIndex(hidden), true);

        Name namedRange = wb.createName();
        namedRange.setNameName("invoiceTypeList");
        namedRange.setRefersToFormula(hiddenName + "!$A$1:$A$" + options.size());

        // 数据验证
        DataValidationHelper helper = sheet.getDataValidationHelper();
        DataValidationConstraint constraint = helper.createFormulaListConstraint("invoiceTypeList");
        // 第 11 列（索引 10）票据类型，从第 2 行开始
        CellRangeAddressList range = new CellRangeAddressList(1, maxRow, 10, 10);
        DataValidation validation = helper.createValidation(constraint, range);
        validation.setShowErrorBox(true);
        validation.setErrorStyle(DataValidation.ErrorStyle.STOP);
        sheet.addValidationData(validation);
    }
}

